﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Configuration; 
using ACP.Business;
using ACP.DTO;

namespace ACP.Web.UI
{
    public partial class Enquiry : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindSupportTypes();
            }
        }

        private void BindSupportTypes()
        {
            try
            {
                List<SupportType> lstSupportTypes = SupportLogic.getSupporTypes();
                ddlSupportTypes.DataSource = lstSupportTypes;
                ddlSupportTypes.DataTextField = "SupportName";
                ddlSupportTypes.DataValueField = "SupportTypeID";
                ddlSupportTypes.DataBind();
            }
            catch (Exception ex)
            {
                acptest_ErrorLog errorLog = new acptest_ErrorLog()
                {
                    //ex.Message, "Page_Load", "Test Page"
                    ErrorMessage = ex.Message,
                    ErrorFunction = "BindSupportTypes()",
                    InsertedTime = DateTime.Now,
                    ModuleName = "Enquiry.aspx"
                };
                ACPErrorLogLogic.ErrorLog(errorLog);
            }
           
        }


        protected void SubmitBtn_Click(object sender, EventArgs e)
        {
            try
            {
                EnquiryInfo enquiryInfo = new EnquiryInfo()
                {
                    SupportTypeID = Convert.ToInt32(ddlSupportTypes.SelectedValue),
                    FullName = txtFullName.Text.Trim(),
                    Email = txtEmail.Text.Trim(),
                    Mobile = txtMobile.Text.Trim(),
                    AltPhone = txtAlternatePhone.Text.Trim(),
                    City = txtCity.Text.Trim(),
                    State = txtState.Text.Trim(),
                    Location = txtLocation.Text.Trim(),
                    PreferredLocation = txtPrefLocation.Text.Trim(),
                    Aligibility = txtEligibility.Text.Trim(),
                    Designation = txtDesignation.Text.Trim(),
                    Company = txtCompany.Text.Trim(),
                    Instructions = messageBox.Text.Trim()
                };

                SupportLogic.InsertSupportInformation(enquiryInfo);
                SendMail();
            }
            catch (Exception ex)
            {
                acptest_ErrorLog errorLog = new acptest_ErrorLog()
                {
                    ErrorMessage = ex.Message,
                    ErrorFunction = "SubmitBtn_Click",
                    InsertedTime = DateTime.Now,
                    ModuleName = "Enquiry.aspx"
                };
                ACPErrorLogLogic.ErrorLog(errorLog);
            }
        }

        private void SendMail()
        {
            try
            {
                //System.Configuration.Configuration config
                //= WebConfigurationManager.OpenWebConfiguration(base.Request.ApplicationPath);
                //AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");

               //System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
               // System.Net.Configuration.MailSettingsSectionGroup settings = (System.Net.Configuration.MailSettingsSectionGroup) config.GetSectionGroup(“system.net/mailSettings”);
 

                //string emailHost = settings.Settings["EmailHost"].Value;
                //string fromAddress = settings.Settings["FromEmailAddr"].Value;
                //string toAddress = settings.Settings["ToEmailAddr"].Value;

                int _mailPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SMTPPort"]);
                string _mailServer = ConfigurationManager.AppSettings["MailServer"];
                string fromAddress = ConfigurationManager.AppSettings["from"];
                string toAddress = ConfigurationManager.AppSettings["toAddress"];
                string smtpUserName = ConfigurationManager.AppSettings["username"];
                string smtpPassword = ConfigurationManager.AppSettings["password"];
 
                SmtpClient smtpClient = new SmtpClient(_mailServer);

                smtpClient.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword);
                
                // Default in IIS will be localhost 
                //smtpClient.Host = "localhost";

                //Default port will be 25
                smtpClient.Port = _mailPort;
                

                MailMessage message = new MailMessage();
                message.IsBodyHtml = false;
                message.Priority = MailPriority.High;
                message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; 

                try
                {
                    message.Subject = "Customer Site: " + this.subjectBox.Text;
                    message.Body = "Sender: " + txtFullName.Text.Trim() + "\n";
                    //message.Body += "Street: " + streetBox.Text.Trim() + "\n";
                    message.Body += "City: " + txtCity.Text.Trim() + "\n";
                    //message.Body += "State: " + stateDropDown.SelectedValue + " " + zipBox.Text.Trim() + "\n";
                    message.Body += "Email: " + txtEmail.Text.Trim() + "\n";
                    message.Body += "\n\n" + this.messageBox.Text + "\n\n";

                    smtpClient.Send(fromAddress, toAddress, message.Subject, message.Body);
                }
                catch (Exception ex)
                {
                    // Display error panel
                    contactLabel.Visible = false;
                    formPanel.Visible = false;
                    errorPanel.Visible = true;

                    // Log error
                    LogError(ex);
                }
                contactLabel.Visible = false;
                formPanel.Visible = false;
                errorPanel.Visible = false;
                successPanel.Visible = true;
            }
            catch (Exception ex)
            {
                acptest_ErrorLog errorLog = new acptest_ErrorLog()
                {
                    ErrorMessage = ex.Message,
                    ErrorFunction = "SendMail()",
                    InsertedTime = DateTime.Now,
                    ModuleName = "Enquiry.aspx"
                };
                ACPErrorLogLogic.ErrorLog(errorLog);
            }
            
        }


        protected void ResetBtn_Click(object sender, EventArgs e)
        {
            txtFullName.Text = "";
           // streetBox.Text = "";
            txtCity.Text = "";
            //stateDropDown.SelectedIndex = 0;
            //zipBox.Text = "";
            txtEmail.Text = "";
            subjectBox.Text = "";
            messageBox.Text = "";

            contactLabel.Text = "Contact Us";
        }


        private void LogError(Exception error)
        {
            LogError(error.Message, error.StackTrace);
        }


        private void LogError(string errMsg, string errTrace)
        {
            // Get programatic access to the email information stored in the web.config file
            Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
            AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");

            // Extract the values based on their key names
            string toAddress = appSettings.Settings["MyEmailAddr"].Value;
            string fromAddress = appSettings.Settings["ToEmailAddr"].Value;
            string emailHost = appSettings.Settings["EmailHost"].Value;
            string mailSubject = "Error in Customer Site: Contact.aspx.cs";
            string mailBody = errMsg + errTrace;

            // Create error notification email
            SmtpClient smtpClient = new SmtpClient(emailHost);
            MailMessage message = new MailMessage(fromAddress, toAddress, mailSubject, mailBody);
            message.IsBodyHtml = false;
            smtpClient.Send(message);
        }
    }
}
